package com.itwxz.forum.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwxz.forum.domain.po.ForumPostCollect;
import com.itwxz.forum.service.ForumPostCollectService;
import com.itwxz.forum.mapper.ForumPostCollectMapper;
import com.itwxz.forum.service.ForumPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author gastronome
* @description 针对表【forum_post_collect(帖子收藏表)】的数据库操作Service实现
* @createDate 2025-05-09 11:26:25
*/
@Service
public class ForumPostCollectServiceImpl extends ServiceImpl<ForumPostCollectMapper, ForumPostCollect>
    implements ForumPostCollectService{

    @Autowired
    private ForumPostService postService;

    @Override
    public SaResult collect(String postId) {
        Long userId = StpUtil.getLoginIdAsLong();

        LambdaQueryWrapper<ForumPostCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ForumPostCollect::getPostId, postId);
        queryWrapper.eq(ForumPostCollect::getUserId, userId);
        ForumPostCollect collect = getOne(queryWrapper);

        if (collect == null) {
            collect = new ForumPostCollect();
            collect.setPostId(Long.valueOf(postId));
            collect.setUserId(userId);

            save(collect);
            // 收藏数 +1
            postService.incrementCollectCount(postId);
            return SaResult.ok("收藏成功").setData(1);
        }else {
            removeById(collect.getId());
            // 收藏数 +1
            postService.decrementCollectCount(postId);
            return SaResult.ok("已取消").setData(0);
        }
    }
}




